/**
 * 页面初始化逻辑：模板及初始化数据的配置及加载
 */
import { getMultiLang } from 'nc-lightapp-front';
import requestApi from './requestApi';
import {setTableExtendCol} from 'src/erm/sscrppublic/common/components/bill';
import {tableExtendButtonClick} from './events';
import attachments from 'uap/common/components/getAttachmentInfo';
import { filterOrigAmount } from './requestApi';
import { beforeUpdatePage, updatePage } from 'src/erm/sscrppublic/common/utils/updatePage';
import { updateBodyData,zzhllxLogic } from './utils';
import { setPageStatus as setPageStatusCommon} from 'src/erm/sscrppublic/common/utils/statusController';
import { toast } from 'nc-lightapp-front';
import _ from 'lodash-es';
import { getDefaultTableButtons } from './ExpenseUtils';

const { getAttachments } = attachments;

// import presetVar from './presetVar';
const head1 = window.presetVar.head.head1;
const body1 = window.presetVar.body.body1;
const pageButton = presetVar.pageButton;
const statusVar = window.presetVar.status;
const areaBtnAction = window.presetVar.areaBtnAction;
let alreadyLoadData = false;
export default function (props) {
    let pageStatus = props.getUrlParam('status');
    let appcodeParam = props.getUrlParam("appcode");
    let pagecodeParam = props.getUrlParam("pagecode");
    window.presetVar.appCode = (appcodeParam==undefined||appcodeParam=='')?props.getSearchParam("c"):appcodeParam;
    window.presetVar.pageCode =  (pagecodeParam==undefined||pagecodeParam=='')?props.getSearchParam("p"):pagecodeParam;
    
    //注意：以后模板的获取需要用 props.createUIDom 替代。

    let createUIDomPromise = new Promise((resolve, reject) => {
        props.createUIDom(
            {},
            (data) => {
                resolve(data);
            }
        )
    })
    let _this = this;
    let getMultiLangPromise = new Promise((resolve, reject) => {
        getMultiLang({
            moduleId: 2011, domainName: 'erm', currentLocale: 'simpchn', callback: (json) => {
                resolve(json);
            }
        });

    })


    Promise.all([createUIDomPromise, getMultiLangPromise]).then((resultList) => {
        let data = resultList[0];
        let json = resultList[1];
        // 全局化组织汇率类型
        let zzhllxs = resultList[0].template.head.items.find((item,index) => {
            return item.attrcode === "zzhllx.rate_category"
        })
        window.presetVar.zzhllxs = zzhllxs && zzhllxs.options
        let meta = data.template;
        let button = data.button;
        this.multiLangJson = json;
        props.use.cardTable(..._.keys(meta.gridrelation));

        // TOP 浏览态也需要显示操作列 ADD
        // 设置按钮模板
        let id = props.getUrlParam('id') ? props.getUrlParam('id') : this.state.billId;
        id = id == "" ? 0 : id;
        if(props.getUrlParam('status') == statusVar.add){ //增加态附件数量 0
            props.button.setButtonTitle('fileManager', json['201102SQFY-0031'] + ' ' + 0 + ' ');
        } else {
            getAttachments(id).then(lists => {
                if (lists.length == 0)  lists = 0;
                props.button.setButtonTitle('fileManager', json['201102SQFY-0031'] + ' ' + lists + ' ');  //附件
            })

        }

        
       

       
        props.meta.setMeta(meta)
        
        //将配置按钮加入pageButton
        Object.keys(meta.gridrelation).forEach(tableCode => {
            if(tableCode !== 'mtapp_detail') {
                let filterBtns = button.filter(btn => btn.key.indexOf(tableCode) > -1)
                filterBtns.forEach(btn => pageButton[btn.key] = btn.key)
            }
        })

        let bodys = Object.keys(meta.gridrelation);
        for (var i = 1; i <= bodys.length; i++) {
            window.presetVar.body["body" + i] = bodys[i - 1];
        }
        window.presetVar.bodys = bodys
        
        //自定义明细添加buttons
        addCustomTableButtons(data, _this);
        //自定义页签添加到createpage中，以支持公式的执行，否则在执行编辑公式时会报未知的错误
        var billinfo = {
            billtype: 'extcard',
            pagecode: presetVar.pageCode, 
            headcode: presetVar.head.head1,
            bodycode: bodys
        }
        this.props.setRelationItemBillinfo(billinfo);

       
        props.button.hideButtonsByAreas(head1);
        props.button.setButtons(button);
        // 设置表格扩展列
        const extendObj = []
        bodys.forEach(bodyCode => {
            extendObj.push({
                tableAreaId: bodyCode,
                onButtonClick: tableExtendButtonClick.bind(this, bodyCode),
                copyRowWithoutCols: [bodyCode]
            })
        })
        setTableExtendCol(props, meta, button, extendObj);


        let transtype = data.context.paramMap.transtype;
        this.setState({ Title: data.context.paramMap.transtype_name });
        let tradetypeParam =  props.getUrlParam("tradetype");
        window.presetVar.billtype= (tradetypeParam==undefined||tradetypeParam==null||tradetypeParam=='')?transtype:tradetypeParam;

        presetVar.pageId = meta.pageid;
        if (props.getUrlParam('status') == statusVar.browse) {
            tplHandle.call(this, meta,button);
            
            //业务数据查询
            let billId = props.getUrlParam('id');
            requestApi.query({
                data: {
                    "openbillid": billId,
                    "pagecode": window.presetVar.pageCode
                },
                success: (data) => {
                    //模板处理
                    tplHandle.call(this, meta,button);

                    props.form.setAllFormValue({[head1]: data.data.head[head1]});
                    //设置表体数据
                    window.presetVar.bodys.forEach((body) => {
                        if (data.data.bodys[body]) {
                            props.cardTable.setTableDataWithResetInitValue(body, data.data.bodys[body]);
                        }
                    });

                    //处理按钮相关状态
                    dataHandle.call(this, data.data.head[head1], props);
                    this.toggleAuditSideBar()

                    // 推送失败展示推送商旅按钮
                    const synctravelstatus = _.get(data, 'data.head.head.rows[0].values.synctravelstatus',{}) 
                    if(synctravelstatus && synctravelstatus.value === '2'){
                        props.button.setButtonVisible([
                            'synctravel',
                        ], true)
                    }
                    


                }
            })

        } else {
            //加载模板默认数据
            let metadata={
                meta:meta,
                props:props
            }
            let _this = this
            requestApi.loadData({
                ...metadata,
                success: (res_meta, billData) => {
                    alreadyLoadData = true;
                    beforeUpdatePage(props)
                    tplHandle.call(this, res_meta ,button);

                    //复制操作
                    let copyFromBillId = props.getUrlParam('copyFromBillId');
                    let changeFromBillId = props.getUrlParam('changeFromBillId');
                    //业务数据查询 (修改操作)
                    let billId = props.getUrlParam('id');
                    if (copyFromBillId) {
                        requestApi.copy({
                            data: {
                                openbillid: copyFromBillId,
                            },
                            success: (data) => {
                                beforeUpdatePage(props);
                                props.form.setAllFormValue({[head1]: data.data.head[head1]});
                                //设置表体数据
                                setTableDataList(props, data.data.bodys)
                                props.cardTable.setStatus(head1, statusVar.edit);
                                //处理按钮相关状态
                                dataHandle.call(this, data.data.head[head1],props);
                                updatePage(props, 'head', window.presetVar.bodys);
                                this.toggleAuditSideBar()
                            }
                            
                        })
                    } else if(changeFromBillId) {
                        requestApi.change({
                            data: {
                                openbillid: changeFromBillId,
                            },
                            success: (data) => {
                                props.form.setAllFormValue({ [head1]: data.data.head[head1] });
                                //设置表体数据
                                window.presetVar.bodys.forEach(body => {
                                    if(data.data.bodys[body]) props.cardTable.setTableData(body, data.data.bodys[body])
                                })
                                //处理按钮相关状态
                                dataHandle.call(this, data.data.head[head1], props);

                                const userjson = _.get(data, 'data.userjson', '{}')
                                try {
                                    const billId = JSON.parse(userjson).accessorybillid;
                                    this.setState({ billId });
                                } catch(err) {
                                    console.error(err);
                                }
                                //处理可编辑状态
                                setPageStatus(statusVar.edit, props);
                                this.toggleAuditSideBar()
                            }
                        })
                    } else if (billId) {
                        requestApi.query({
                            data: {
                                "openbillid": billId,
                                "pagecode": window.presetVar.pageCode
                            },
                            success: (data) => {
                                props.form.setAllFormValue({[head1]: data.data.head[head1]});
                                //设置表体数据
                                // updateBodyData(props, data.data.bodys)
                                window.presetVar.bodys.forEach((bodyCode) =>{
                                    data.data.bodys[bodyCode]&&props.cardTable.setTableData(bodyCode, data.data.bodys[bodyCode]);
                                })
                                setPageStatus( props.getUrlParam('status'), props)
                                this.toggleAuditSideBar()
                                // 推送失败展示推送商旅按钮
                                const synctravelstatus = _.get(data, 'data.head.head.rows[0].values.synctravelstatus',{}) 
                                if(synctravelstatus && synctravelstatus.value === '2'){
                                    props.button.setButtonVisible([
                                        'synctravel',
                                    ], true)
                                }
                            }
                        })
                    }
                    let org_currinfo = this.props.form.getFormItemsValue(window.presetVar.head.head1,'org_currinfo');
                    // let bzbm = billData.head.head.rows[0].values.pk_currtype.value //获取币种
                    if( parseFloat(org_currinfo.value) == parseFloat(1) ||  pageStatus == statusVar.browse)
                    {
                        this.props.form.setFormItemsDisabled(window.presetVar.head.head1,{'org_currinfo':true});
                    }else{
                        this.props.form.setFormItemsDisabled(window.presetVar.head.head1,{'org_currinfo':false});
                    }
                    let currentrow_bzbm = billData.head.head.rows[0].values.pk_currtype;
                    let rate_category = billData.head.head.rows[0].values['zzhllx.rate_category'];
                    zzhllxLogic(currentrow_bzbm,rate_category,'head',props,'org_currinfo')
                    props.form.setAllFormValue({[head1]: billData.head[head1]});
                    //设置表体数据
                    // updateBodyData(props, billData.bodys)
                    window.presetVar.bodys.forEach((bodyCode) =>{
                        billData.bodys[bodyCode]&&props.cardTable.setTableData(bodyCode, billData.bodys[bodyCode]);
                    })
                    setPageStatus( props.getUrlParam('status'), props)
                    updatePage(props, 'head', window.presetVar.bodys);
                    this.toggleAuditSideBar()
                }
            });

        }
    }).then(() => {
        //请求附件控制状态
        requestApi.getAttachmentControlParams({
            data: { transtypecode: window.presetVar.billtype },
            success: (data) => {
                // data.enablemodifyaccessory  审批中是否允许修改
                // data.mustuploadaccessory 是否必须上传附件
                window.presetVar.attachmentControl = {
                    modify: data.enablemodifyaccessory,
                    necessary: data.mustuploadaccessory
                }
            }
        })
    })
 /**
     * 自定义明细 按钮, 往data里写入自定义的button数据
     * @param {button:[], template:{}, context:{}} data
     */
  function addCustomTableButtons(data, that) {
    //'invoice_relate','invoice_cancel'

    // console.log('data.button',data.button,data.template)
    if (!data.button || !data.button.length) return
    const buttons = data.button;
    const keys = Object.keys(data.template.gridrelation);
    const excludeKeys = ['mtapp_detail',];
    keys.forEach(key => {
        if(!excludeKeys.includes(key)) {
            //如果不在这里的都是自定义明细
            const addButtons = getDefaultTableButtons(key)

            addButtons.forEach(btn => {
                btn.title = that.multiLangJson[btn.title];

                buttons.push(btn);
            })
        }
        

    })
    // console.log('按钮===',buttons,props)

}
    function tplHandle(meta, button) {
        // BTM 浏览态也需要显示操作列
        //肩部按钮可见状态：页面和表格的肩部按钮，这里逻辑根据实际业务实现。
        let btnsVisibleObj = {};
        let isAddOrEditStatus =  pageStatus == statusVar.edit || pageStatus == statusVar.add;
        let isBrowseStatus = pageStatus == statusVar.browse

        //如果下列按钮业务逻辑固定，后续可以封装到组件中。
        for (let btnKey in pageButton) {
            btnsVisibleObj[btnKey] = false;
        }
        if (isAddOrEditStatus) { //添加或编辑态 隐藏下列按钮
            btnsVisibleObj['pageSave'] = true;
            btnsVisibleObj['billSubmit'] = false;
            btnsVisibleObj['billSaveSubmit'] = true;
            btnsVisibleObj['fileManager'] = true;
            btnsVisibleObj['mtapp_detail_Add'] = true;
            btnsVisibleObj['save_temp'] = true;

            btnsVisibleObj['mtapp_detail_Delete'] = true;
            btnsVisibleObj['mtapp_detail_Copy'] = true;
            btnsVisibleObj['mtapp_detail_Insert'] = true;

            btnsVisibleObj['linkVoucher'] = false;
            btnsVisibleObj['linkBudget'] = false;
            btnsVisibleObj['buttongroup4_m'] = false;
            //新增态时取消按钮显示
            if (pageStatus == statusVar.add || pageStatus == statusVar.edit) {
                btnsVisibleObj['pageClose'] = true;
            }

        }
        if (isBrowseStatus) { //浏览态 隐藏下列按钮
            btnsVisibleObj['pageEdit'] = true;
            btnsVisibleObj['pageCopy'] = true;
            btnsVisibleObj['pageDel'] = true;
            btnsVisibleObj['pagePrint'] = true;
            btnsVisibleObj['imageShow'] = true;
            btnsVisibleObj['imageUpload'] = true;
            btnsVisibleObj['billView'] = true;
            btnsVisibleObj['linkVoucher'] = false;
            btnsVisibleObj['linkBudget'] = false;
            btnsVisibleObj['billSaveSubmit'] = false;
            btnsVisibleObj['pageClose'] = false;
            btnsVisibleObj['buttongroup4_m'] = true;
            btnsVisibleObj["save_temp"] = false;//暂存
            
        }

        props.button.setButtonsVisible(btnsVisibleObj);
        setTableButtonsVisibleWithStatus(props)

        //table扩展按钮弹窗确认框设置
         let multiLang = props.MutiInit.getIntl(2011);
         window.presetVar.bodys.forEach(bodyCode => {
             props.button.setPopContent(bodyCode + areaBtnAction.del,multiLang && multiLang.get('201102SQFY-0032')/**'确认要删除该信息吗？'**/) /* 设置操作列上删除按钮的弹窗提示 */
         })

        //无金额申请
        if (window.presetVar.noamount) {
            meta = filterOrigAmount(meta)
        }

        //设置模板
        props.meta.setMeta(meta);
    }

}

//改变表头表体组件的编辑状态
function setPageStatus(pageStatus, props) {
    let changeStatus = null;
    switch (pageStatus) {
        case statusVar.edit:
        changeStatus  = statusVar.edit;
        break;
        case statusVar.add:
        changeStatus  = statusVar.add;
        break;
        case statusVar.browse:
        changeStatus = statusVar.browse;
        break;
    }
    setPageStatusCommon(props, props.meta.getMeta(), ['head'], window.presetVar.bodys, changeStatus)
}

/**
 * 设置表体数据
 * @param {*} props
 * @param {*} bodys  返回表体数据
 */
function setTableDataList(props, bodys={}) {
    Object.keys(bodys).forEach(body => {
        const bodyData = bodys[body]
        props.cardTable.setTableData(body, bodyData, null, false)
    })
}

function dataHandle(head,props) {
    const that = this;
    //处理数据和按钮状态
    if (head == null || head.rows[0] == null || head.rows[0].values == null) {
        return;
    }
    let scene = props.getUrlParam('scene');
    let deal = props.getUrlParam("deal");
    let sxbz = head.rows[0].values.effectstatus.value;//单据生效状态
    let spzt = head.rows[0].values.apprstatus.value;//审批状态
    let djzt =head.rows[0].values.billstatus.value//单据状态
    this.setState({djzt})
    let gbzt = head.rows[0].values.close_status.value;//关闭状态
    let btnsVisibleObj = {};
    let pageStatus = props.getUrlParam('status');
    let isAddOrEditStatus =  pageStatus == statusVar.edit || pageStatus == statusVar.add;
    if(isAddOrEditStatus)
    {
        //如果下列按钮业务逻辑固定，后续可以封装到组件中。
        for (let btnKey in pageButton) {
            btnsVisibleObj[btnKey] = false;
        }
        //单据提交之后不显示保存提交按钮
        if(spzt==-1 || spzt==null){
            btnsVisibleObj[pageButton.billSaveSubmit] = true;
        }else{
            btnsVisibleObj[pageButton.billSaveSubmit] = false;
        }
        btnsVisibleObj[pageButton.pageSave] = true;
        btnsVisibleObj[pageButton.billSubmit] = false;
        btnsVisibleObj[pageButton.fileManager] = true;
        btnsVisibleObj[pageButton['mtapp_detail_Add']] = true;
        // TOP 浏览态也需要显示操作列 ADD
        btnsVisibleObj['mtapp_detail_Delete'] = true;
        btnsVisibleObj['mtapp_detail_Copy'] = true;
        btnsVisibleObj['mtapp_detail_Insert'] = true;
        // BTM 浏览态也需要显示操作列
        btnsVisibleObj[pageButton['linkVoucher']] = false;
        btnsVisibleObj[pageButton['linkBudget']] = false;
        btnsVisibleObj['buttongroup4_m'] = false;
        btnsVisibleObj['save_temp'] = true;
        //新增态时取消按钮显示
        if (pageStatus == statusVar.add || pageStatus == statusVar.edit) {
            btnsVisibleObj[pageButton.pageClose] = true;
        }

        // 审批进行中  提交状态 附件可编辑受控
        if ((spzt == 2 || spzt == 3) && window.presetVar.attachmentControl) {
            that && that.setState({uploaderBtnDisable: !window.presetVar.attachmentControl.modify})
        } else if (spzt == -1) {
            //单据不在审批中,默认可修改
            that && that.setState({uploaderBtnDisable: false})
        }
        if(djzt == '1') {
            if(pageStatus == 'add'){
                btnsVisibleObj["save_temp"] = true;//暂存
            }else if(pageStatus == 'edit'){
                btnsVisibleObj["save_temp"] = false;//暂存
            }
        }

       //设置编辑状态
       props.button.setButtonsVisible(btnsVisibleObj);
       setTableButtonsVisibleWithStatus(props)
       
    }else{
        let isBrowseStatus = pageStatus == statusVar.browse
    for (let btnKey in pageButton) {
        btnsVisibleObj[btnKey] = false;
        //来源于审批人门户、作业处理时 显示 ：修改、影像扫描|影像查看、联查预算、联查凭证、更多（联查审批情况、联查单据、附件、关闭/重启、打印）
        if (scene == 'approve' || scene == 'approvesce' || scene == 'zycl') {
            if (
                spzt == '1' &&
                (btnKey == pageButton.imageShow ||
                    btnKey == pageButton.imageUpload ||
                    btnKey == pageButton.pagePrint ||
                    btnKey == pageButton.billView ||
                    btnKey == pageButton.billApprove
                    )
            ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else if (
                btnKey == pageButton.imageShow ||
                btnKey == pageButton.imageUpload ||
                btnKey == pageButton.pagePrint ||
                btnKey == pageButton.billView ||
                btnKey == pageButton.billApprove ||
                btnKey == pageButton.pageEdit
            ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
            //审批中心打开的单据点击修改时需要处理按钮状态
        }
        //来源于作业查询时 显示 ：影像查看、联查预算、联查凭证、更多（联查审批情况、联查单据、打印）
        else if (scene == 'zycx' || scene == 'bzcx' || scene == 'fycx') {
            if (
                btnKey == pageButton.imageShow ||
                btnKey == pageButton.pagePrint ||
                btnKey == pageButton.billView ||
                btnKey == pageButton.billApprove ||
                btnKey == pageButton.fileManager
            ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
        } else {
            //审批状态为初始态，显示：修改|删除|复制、提交、影像扫描|影像查看、更多（附件、作废、打印）
            if (
                spzt == '-1' &&
                (btnKey == pageButton.pagePrint ||
                    btnKey == pageButton.pageCopy ||
                    btnKey == pageButton.imageShow ||
                    btnKey == pageButton.imageUpload ||
                    btnKey == pageButton.billSubmit ||
                    btnKey == pageButton.billInvalid ||
                    btnKey == pageButton.pageEdit ||
                    btnKey == pageButton.pageDel)
            ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
            //审批状态为提交态，显示：复制、收回、影像扫描|影像查看、更多（联查审批情况、附件、打印）
            else if (
                (spzt == '3' || spzt == '2') &&
                (btnKey == pageButton.pagePrint ||
                    btnKey == pageButton.pageCopy ||
                    btnKey == pageButton.imageShow ||
                    btnKey == pageButton.imageUpload ||
                    btnKey == pageButton.billApprove)
            ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
            //审批状态为通过态，显示：复制、影像查看、更多（联查审批情况、联查单据、附件、关闭/重启、打印）
            else if (
                spzt == '1' &&
                (btnKey == pageButton.pageCopy ||
                    btnKey == pageButton.imageShow ||
                    btnKey == pageButton.pagePrint ||
                    btnKey == pageButton.billView ||
                    btnKey == pageButton.billApprove
                )
            ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else if (spzt == '1' && btnKey == pageButton.pageChange && window.presetVar.canChange) {
                //变更是否显示，需要根据后端字段来判断
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
        }

        const inc_keys = ['approve', 'approvesce', 'zycl', 'zycx', 'bzcx', 'fycx']
        //已提交显示收回按钮
        if (btnKey == 'billRecall' && !inc_keys.includes(scene)) {
            if (spzt == '3') {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }

        //已完成单据，隐藏影像扫描，附件管理
        if (btnKey == pageButton.imageUpload || btnKey == pageButton.fileManager) {
            if (sxbz == '1') {
                if (scene != 'bzcx' && scene != 'fycx') {
                    btnsVisibleObj[btnKey] = false;
                }
                //审批完成的需要查看附件
                if (scene === 'bz' || scene === 'lc') {
                    btnsVisibleObj[pageButton.fileManager] = true;
                    this.setState({ uploaderBtnDisable: true });
                }
            } else {
                if (scene != 'zycx' && scene != 'bzcx' && scene != 'fycx') {
                    btnsVisibleObj[btnKey] = isBrowseStatus;
                }
            }
        }
        //已完成、未关闭的单据允许关闭
        if (btnKey == pageButton.billClose) {
            if (sxbz == '1' && gbzt == '2' && scene != 'zycx' && scene != 'bzcx' && scene != 'fycx') {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }
        //已关闭的单据允许重启
        if (btnKey == pageButton.billEnable && scene != 'zycx' && scene != 'bzcx' && scene != 'fycx') {
            if (sxbz == '1' && gbzt == '1') {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }

        //已完成单据显示联查功能
        if (btnKey == pageButton.billView) {
            if (sxbz == '1') {
                btnsVisibleObj[btnKey] = true;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }
        //审批中心或作业平台打开
        if (btnKey == 'linkVoucher' || btnKey == 'linkBudget') {
            if (scene == 'approve' || scene == 'approvesce' || scene == 'zycl' || scene == 'zycx' || scene == 'fycx') {
                btnsVisibleObj[pageButton['linkVoucher']] = true;
                btnsVisibleObj[pageButton['linkBudget']] = true;
            } else {
                btnsVisibleObj[pageButton['linkVoucher']] = false;
                btnsVisibleObj[pageButton['linkBudget']] = false;
            }
        }

        //作废的单据影藏保存提交修改等状态
        if (djzt == '-1') {
            if (btnKey == pageButton.pageCopy || btnKey == pageButton.imageShow || btnKey == pageButton.pagePrint) {
                btnsVisibleObj[btnKey] = true;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }

        //暂存后隐藏提交按钮
        if (djzt == "0") {
            btnsVisibleObj[pageButton.billSubmit] = false;
        }
    }
    }

    

    if(deal!=undefined&&(deal=='handon'||deal=='adjust'||deal=='sscreject'||deal=='handled')) btnsVisibleObj[pageButton.pageEdit] = false;

    window.presetVar.bodys.forEach(bodyCode => {
        if( pageStatus == statusVar.browse) {
            props.button.setButtonsVisible({
                [ bodyCode +'_Add']: false,
                // TOP 浏览态也需要显示操作列 ADD
                [ bodyCode +'_Delete'] : false,
                [ bodyCode +'_Copy'] : false,
                [ bodyCode +'_Insert'] : false,
                [ bodyCode + '_Edit'] : true
            });
        } else {
            props.button.setButtonsVisible({
                [ bodyCode +'_Add']: true,
                [ bodyCode +'_Delete'] : true,
                [ bodyCode +'_Copy'] : true,
                [ bodyCode +'_Insert'] : true
            });
        }
    })


    //来源于报表联查的单据
    const showKeys = [pageButton.billView, pageButton.billApprove, pageButton.imageShow, pageButton.pagePrint, pageButton.fileManager, 'LinkBudget', 'LinkVoucher']
    if(scene=='sscermlink'){
        for (let btnKey in pageButton) {
            if( showKeys.includes(btnKey) ) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }
    }
    if(scene == 'bzcx') {
        if( djzt == '-1' ) {
            btnsVisibleObj[pageButton.pageCopy] = false
        }
    }

    if (spzt == 1)  {
        that&&that.setState({uploaderBtnDisable: true})
        btnsVisibleObj[pageButton.pageEdit] = false
    }

    // 审批进行中  提交状态 附件可编辑受控
    if ((spzt == 2 || spzt == 3) && window.presetVar.attachmentControl) {
        that && that.setState({uploaderBtnDisable: !window.presetVar.attachmentControl.modify})
    } else if (spzt == -1) {
        //单据不在审批中,默认可修改
        that && that.setState({uploaderBtnDisable: false})
    } else if (spzt == 1) {
        btnsVisibleObj[pageButton.fileManager] = true;
        that && that.setState({uploaderBtnDisable: true})
    }

    if(window.presetVar.linkHis) {
        btnsVisibleObj[pageButton.linkQueryChangeHistory] = true
    } else {
        btnsVisibleObj[pageButton.linkQueryChangeHistory] = false
    }

    props.button.setButtonsVisible(btnsVisibleObj);
    setTableButtonsVisibleWithStatus(props)
}


export {dataHandle}

function routeChange(props){

    let pagestatusVar = props.getUrlParam('status'); //重新设置状态变量
    //openBillId = props.getUrlParam('id'); //重设单据id
    //presetVar.openBillId = openBillId;
    window.presetVar.status = pagestatusVar;

    let isShowTableExtCol = false; //是否显示表格扩展列
    switch (pagestatusVar) {
        case statusVar.browse:
            isShowTableExtCol = false;
            break;
        case statusVar.add:
        case statusVar.edit:
            isShowTableExtCol = true;

            let metadata = {
                meta: props.meta.getMeta(),
                props: props
            }
            //只有以添加/编辑态打开单据时，才会在初始化函数中调用loadData请求，所以如果从浏览态直接打开页面时，是不会加载loaddata的，所以如果页面此时从浏览态转到添加/编辑态，需要加载loadData
            if (!alreadyLoadData) {
                requestApi.loadData({
                    ...metadata,
                    success: (meta) => {
                        alreadyLoadData = true;
                        props.meta.setMeta(meta);
                        this.toggleAuditSideBar()
                    }
                })
            }
            break;
    }

    let copyFromBillId = props.getUrlParam('copyFromBillId');
    let changeFromBillId = props.getUrlParam('changeFromBillId');
    if (copyFromBillId) {
        requestApi.copy({
            data: {
                openbillid: copyFromBillId,
            },
            success: (data) => {
                beforeUpdatePage(props)
                props.form.setAllFormValue({ [head1]: data.data.head[head1] });
                //设置表体数据
                window.presetVar.bodys.forEach(body => {
                    if(data.data.bodys[body]) props.cardTable.setTableData(body, data.data.bodys[body])
                })
                //处理按钮相关状态
                dataHandle.call(this, data.data.head[head1], props);

                //处理可编辑状态
                setPageStatus(statusVar.edit, props);
                updatePage(props, 'head', window.presetVar.bodys);
                const headData = data.data.head[head1]
                requestApi.getAttachmentControlParams({
                    data: { transtypecode: window.presetVar.billtype },
                    success: (data) => {
                        // data.enablemodifyaccessory  审批中是否允许修改
                        // data.mustuploadaccessory 是否必须上传附件
                        window.presetVar.attachmentControl = {
                            modify: data.enablemodifyaccessory,
                            necessary: data.mustuploadaccessory
                        }
                        this.toggleAuditSideBar()
                        dataHandle.call(this, headData, props);
                    }
                })
            }
        })//复制单据。 因为复制单据操作 既能在初始态触发，又可以被交互态触发。所以没有把该函数写在按钮事件上。
    } else if(changeFromBillId) {
        requestApi.change({
            data: {
                openbillid: changeFromBillId,
            },
            success: (data) => {
                props.form.setAllFormValue({ [head1]: data.data.head[head1] });
                //设置表体数据
                window.presetVar.bodys.forEach(body => {
                    if(data.data.bodys[body]) props.cardTable.setTableData(body, data.data.bodys[body])
                })
                //处理按钮相关状态
                dataHandle.call(this, data.data.head[head1], props);

                //处理可编辑状态
                setPageStatus(statusVar.edit, props);

                const userjson = _.get(data, 'data.userjson', '{}')
                try {
                    const billId = JSON.parse(userjson).accessorybillid;
                    this.setState({ billId });
                } catch(err) {
                    console.error(err);
                }

                if(window.change_accessorybillid) {
                    getAttachments(window.change_accessorybillid).then(lists => {
                        if (lists.length == 0)  lists = 0;
                        props.button.setButtonTitle('fileManager', '附件' + ' ' + lists + ' ');  //附件
                    })
                }
                const headData = data.data.head[head1]
                requestApi.getAttachmentControlParams({
                    data: { transtypecode: window.presetVar.billtype },
                    success: (data) => {
                        window.presetVar.attachmentControl = {
                            modify: data.enablemodifyaccessory,
                            necessary: data.mustuploadaccessory
                        }
                        this.toggleAuditSideBar()
                        dataHandle.call(this, headData, props);
                    }
                })
            },
            error:(data)=>{
              toast({ content: data.message, color: 'danger' });
              props.button.setButtonsVisible({
               [pageButton.pageChange]: false
              });
            }
        })
    } else {
        let headData = props.form.getAllFormValue(head1);
        this.toggleAuditSideBar()
        //根据单据状态，改变按钮的显示的状态
        dataHandle.call(this, headData, props);
    }

    //处理可编辑状态
    setPageStatus(pagestatusVar, props);
}
export {routeChange}

// 表体按钮根据status显示控制
function setTableButtonsVisibleWithStatus(props) {
    let pageStatus = props.getUrlParam('status');
    const isAddOrEditStatus =  pageStatus == statusVar.edit || pageStatus == statusVar.add;
    const isBrowseStatus = !isAddOrEditStatus
    const btnsVisibleObj = {}
    Object.keys(pageButton).forEach(one => {
        //browse状态都隐藏
        if ((one.indexOf('_Add') > -1 || one.indexOf('_Edit') > -1 || one.indexOf('_Copy') > -1 ||  one.indexOf('_Insert') > -1 || one.indexOf('_Delete') > -1) && isBrowseStatus) {
            btnsVisibleObj[one] = false;
        }

        if ((one.indexOf('_Add') > -1 || one.indexOf('_Edit') > -1 || one.indexOf('_Copy') > -1 ||  one.indexOf('_Insert') > -1 || one.indexOf('_Delete') > -1) && isAddOrEditStatus) {
                btnsVisibleObj[one] = true;
        }
    })
    window.presetVar.bodys.forEach(bodeCode => {
        btnsVisibleObj[`${bodeCode}_Edit`] = true
    })
    props.button.setButtonsVisible(btnsVisibleObj)
}

function setDefautValueAfterBodyAdd(props, tablecode) {
    const moudleid = tablecode;
    const multiLang = props.MutiInit.getIntl(2011);

    //rowIndex不能使用getAllRows,要使用getVisibleRows,前者会带出删除的行,在删除行再新增的情况下，rowIndex计算错误
    let rowIndex = props.cardTable.getVisibleRows(moudleid).length - 1;

    let keys = ['bzbm','dwbm','deptid','jkbxr','paytarget','receiver','skyhzh','hbbm','customer','custaccount','bbhl','groupbbhl','globalbbhl','zzhllx','zzhllyrq',
    "pk_customer", "pk_customer_v", "pk_supplier", "pk_supplier_v"]
    let default_values = {}
    keys.forEach(key => {
        let headvalue = props.form.getFormItemsValue(window.presetVar.head.head1,key);
        default_values[key] = headvalue
    })
    props.cardTable.setValByKeysAndIndex(moudleid, rowIndex, default_values)

    let paytarget = props.cardTable.getDataByIndex(moudleid, rowIndex).values['paytarget'].value
    let nullvalue = {
        display: null,
        value : null
    }

    // 增行时，本币汇率、汇率类型、汇率来源日期，需根据表头来设置表体其编辑性
    let bbhlFlag = props.form.getFormItemsDisabled('head', 'bbhl'); //表头本币汇率编辑性
    let zzhllxFlag = props.form.getFormItemsDisabled('head', 'zzhllx'); //表头本币汇率类型编辑性
    let zzhllyrqFlag = props.form.getFormItemsDisabled('head', 'zzhllyrq'); //表头本币汇率日期编辑性
    // 表头中本币种、汇率类型更改后，表体中本币汇率、汇率类型、汇率来源日期需同时控制其编辑性
    let editkeys = []
    let unedikeys = []
    bbhlFlag ? unedikeys.push('bbhl') : editkeys.push('bbhl')
    zzhllxFlag ? unedikeys.push('zzhllx') : editkeys.push('zzhllx')
    zzhllyrqFlag ? unedikeys.push('zzhllyrq') : editkeys.push('zzhllyrq')
    props.cardTable.setEditableByIndex(moudleid, rowIndex, editkeys, true)
    props.cardTable.setEditableByIndex(moudleid, rowIndex, unedikeys, false)
}
export { setDefautValueAfterBodyAdd }
